<template>
  <div class="map-view-container">
    <div class="sidebar" :class="{ 'collapsed': sidebarCollapsed }">
      <div class="sidebar-header">
        <span>在线查询</span>
        <div class="header-actions">
          <el-button
              type="primary"
              size="small"
              @click="toggleCoordinatePick"
              :class="{ 'active': isPickingCoordinates }"
          >
            {{ isPickingCoordinates ? '取消拾取' : '坐标拾取' }}
          </el-button>
          <el-button
              circle
              size="small"
              @click="toggleSidebar"
              class="collapse-btn"
          >
            <el-icon :class="{ 'rotate-icon': sidebarCollapsed }">
              <ArrowLeft />
            </el-icon>
          </el-button>
        </div>
      </div>
      <div class="control-search-box" v-show="!sidebarCollapsed">
        <SearchBox
            ref="searchBoxRef"
            @search="handleSearch"
            @clear="handleClear"
        />
      </div>
    </div>

    <div class="map-wrapper" :style="{ 'margin-left': sidebarCollapsed ? '0' : '350px' }">
      <Map
          ref="mapRef"
          :username="username"
          :user-avatar="userAvatar"
          :is-logged-in="isLoggedIn"
          :is-picking-coordinates="isPickingCoordinates"
          @map-loaded="handleMapLoaded"
          @location-found="handleLocationFound"
          @map-click="handleMapClick"
          @zoom-change="handleZoomChange"
      />
      <div
          class="sidebar-toggle-btn"
          v-if="sidebarCollapsed"
          @click="toggleSidebar"
      >
        <el-icon><ArrowRight /></el-icon>
      </div>
    </div>
  </div>
</template>

<script>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import Map from './Map.vue'
import SearchBox from './SearchBox.vue'
import { convertBD09ToWGS84, convertCoordinate } from '../utils/baiduConvert.js'
import api from '../api/auth.js'
import { ArrowLeft, ArrowRight } from '@element-plus/icons-vue'

export default {
  name: 'MapView',
  components: {
    Map,
    SearchBox,
    ArrowLeft,
    ArrowRight
  },
  props: {
    username: { type: String, default: '游客' },
    userAvatar: { type: String, default: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png' },
    isLoggedIn: { type: Boolean, default: false }
  },
  data() {
    return {
      sidebarCollapsed: false
    }
  },
  setup() {
    const mapRef = ref(null)
    const searchBoxRef = ref(null)
    const isPickingCoordinates = ref(false)
    const points = ref([])

    return { mapRef, searchBoxRef, isPickingCoordinates, points }
  },
  methods: {
    handleMapLoaded(map) {
      // Map loaded
    },
    toggleSidebar() {
      console.log('Toggling sidebar, current state:', this.sidebarCollapsed);
      this.sidebarCollapsed = !this.sidebarCollapsed;
      if (this.mapRef && this.mapRef.map) {
        setTimeout(() => {
          this.mapRef.map.reset(); // Trigger map resize (adjust to your map library's method)
        }, 300);
      }
    },
    toggleCoordinatePick() {
      this.isPickingCoordinates = !this.isPickingCoordinates;
      ElMessage.info(this.isPickingCoordinates ? '请在地图上点击选择坐标位置，拾取后将直接查询街景' : '已取消坐标拾取模式');
    },
    async handleMapClick(e) {
      if (!this.isPickingCoordinates) return;
      const bdPoint = e;
      try {
        const wgsPoint = await convertBD09ToWGS84(bdPoint.lng, bdPoint.lat, 'bd2wgs');
        ElMessage.info(`WGS84 坐标: ${wgsPoint.lng.toFixed(6)}, ${wgsPoint.lat.toFixed(6)}`);
        this.mapRef.addMarker(bdPoint.lng, bdPoint.lat);
        this.searchBoxRef.fetchStreetViewImages(bdPoint.lng, bdPoint.lat);
        ElMessage.success(`已获取 BD09 坐标并查询街景: ${bdPoint.lng.toFixed(6)}, ${bdPoint.lat.toFixed(6)}`);
        this.isPickingCoordinates = false;
      } catch (error) {
        ElMessage.error('坐标转换或街景查询失败: ' + error.message);
      }
    },
    async handleSearch(coords) {
      try {
        const bdPoint = await convertCoordinate(coords.lng, coords.lat, 'wgs2bd');
        this.mapRef.setMapCenter(bdPoint.lng, bdPoint.lat);
        this.mapRef.addMarker(bdPoint.lng, bdPoint.lat);
        ElMessage.success(`已定位到: ${bdPoint.lng.toFixed(6)}, ${bdPoint.lat.toFixed(6)}`);
        this.searchBoxRef.fetchStreetViewImages(bdPoint.lng, bdPoint.lat);
        await this.fetchPoints(bdPoint.lng, bdPoint.lat);
      } catch (error) {
        ElMessage.error('坐标转换失败: ' + error.message);
      }
    },
    handleClear() {
      this.mapRef.clearOverlays();
      ElMessage.info('地图上的标记已清除');
    },
    async fetchPoints(minX, minY, maxX, maxY) {
      try {
        const response = await api.getPoints(minX, minY, maxX, maxY);
        if (response.data.code === "200") {
          this.points = response.data.data;
          this.clearPoints();
          this.points.forEach(point => {
            const title = `${point.name || '未命名地点'}\nOSM ID: ${point.osm_id}`;
            this.mapRef.addMarker(
                point.longitude,
                point.latitude,
                title,
                { icon: new BMapGL.Icon('marker.png', new BMapGL.Size(30, 30)) }
            );
          });
          ElMessage.success(`加载了 ${this.points.length} 个地点`);
        } else {
          ElMessage.error(response.data.message || "获取数据失败");
        }
      } catch (error) {
        ElMessage.error(`请求失败: ${error.message}`);
      }
    },
    clearPoints() {
      if (this.mapRef) {
        this.mapRef.clearOverlays();
      }
      this.points = [];
    },
    handleLocationFound(point) {
      this.searchBoxRef.setCoordinates(point.lat, point.lng);
    },
    handleZoomChange({ zoom, bounds, clear }) {
      if (clear) {
        this.clearPoints();
        return;
      }
      if (zoom >= 13 && bounds) {
        try {
          this.fetchPoints(bounds.swLng, bounds.swLat, bounds.neLng, bounds.neLat);
        } catch (error) {
          ElMessage.error('获取点数据失败: ' + error.message);
        }
      }
    }
  }
}
</script>

<style scoped>
.map-view-container {
  display: flex;
  width: 100%;
  height: 100vh;
  margin: 0;
  padding: 0;
  overflow: hidden;
}

.sidebar {
  width: 280px;
  background: #ffffff;
  display: flex;
  flex-direction: column;
  height: 100vh;
  margin: 0;
  padding: 0;
  box-shadow: 2px 0 5px rgba(0, 0, 0, 0.1);
  z-index: 1002;
  transition: width 0.3s ease;
}

.sidebar.collapsed {
  width: 0;
  overflow: hidden;
  padding: 0;
}

.sidebar.collapsed .search-box {
  display: none;
}

.sidebar-header {
  background: #409EFF;
  color: white;
  padding: 15px 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
  font-weight: bold;
  margin: 0;
}

.sidebar-header .el-button {
  margin-left: 10px;
}

.sidebar-header .el-button.active {
  background: #67c23a;
  border-color: #67c23a;
}

.search-box {
  padding: 20px;
  flex: 1;
  overflow-y: auto;
}

.map-wrapper {
  flex: 1;
  position: relative;
  height: 100vh;
  margin: 0;
  padding: 0;
  transition: margin-left 0.3s ease;
  z-index: 0;
}

.sidebar-toggle-btn {
  position: absolute;
  top: 50%;
  left: 0;
  transform: translateY(-50%);
  background: #409EFF;
  color: white;
  padding: 10px;
  cursor: pointer;
  z-index: 1003;
  border-radius: 0 5px 5px 0;
  box-shadow: 2px 0 5px rgba(0, 0, 0, 0.1);
}

.sidebar-toggle-btn .el-icon {
  font-size: 20px;
}

.rotate-icon {
  transform: rotate(180deg);
  transition: transform 0.3s ease;
}
</style>
